<template>
    <div style="background-color: white;padding: 20px">
      <el-tabs v-model="activeName">
        <el-tab-pane label="个人信息" name="user">

          <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="demo-ruleForm" style="width: 614px">
            <el-form-item label="头像" >
              <el-upload action="" class="avatar-uploader"
                         accept=".jpg,.png,.jpeg" :show-file-list=false
                :http-request="uploadFile"
                :before-upload="beforeAvatarUpload">
                <img v-if="form.avatar" :src="form.avatar" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </el-form-item>
            <el-form-item label="姓名" >
              <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
            </el-form-item>
            <el-form-item label="用户名" >
              <el-input v-model="form.realName" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm('form')">
                <i class="el-icon-check"></i>提交
              </el-button>
              <el-button @click="resetForm('form')">
                <i class="el-icon-delete"></i>
                清空</el-button>
            </el-form-item>
          </el-form>

        </el-tab-pane>
        <el-tab-pane label="修改密码" name="password">

          <el-form :model="passwordForm" :rules="passwordRules" ref="passwordForm" label-width="100px" class="demo-ruleForm" style="width: 614px">
            <el-form-item label="原密码" prop="oldPassword">
              <el-input v-model="passwordForm.oldPassword" placeholder="请输入 原密码" show-password></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="passwordForm.newPassword" placeholder="请输入 新密码" show-password></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="newPassword1">
              <el-input v-model="passwordForm.newPassword1" placeholder="请输入 确认密码" show-password></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="modifyPassword('passwordForm')">
                <i class="el-icon-check"></i>提交
              </el-button>
              <el-button @click="resetForm('passwordForm')">
                <i class="el-icon-delete"></i>
                清空</el-button>
            </el-form-item>
          </el-form>

        </el-tab-pane>
      </el-tabs>
    </div>
</template>

<script>
    import {getUserDetail, update, updatePassword} from "@/api/system/user";
    import {uploadOss} from '@/util/file'
    export default {
        name: "index",
        data() {
            var checkphone = (rule, value, callback) => {
                const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
                console.log(reg.test(value));
                if (reg.test(value)) {
                    callback();
                } else {
                    return callback(new Error('请输入正确的手机号'));
                }
            };
            // 密码确认
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    if (this.passwordForm.newPassword !== '') {
                        this.$refs.passwordForm.validateField('newPassword1');
                    }
                    callback();
                }
            };
            var validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.passwordForm.newPassword) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            return {
                header: {},
                activeName: 'user',
                form: {
                    avatar:'',
                    name: '',
                    realName: '',
                    phone: '',
                    email: ''
                },
                rules:{
                    phone:[
                        {required: false, validator: checkphone, trigger: 'blur'}
                    ],
                    email: [
                      { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                    ],
                },
                passwordForm:{
                    oldPassword: '',
                    newPassword: '',
                    newPassword1: ''
                },
                passwordRules:{
                    oldPassword: [{
                        required: true, message: '请输入原密码', trigger: 'blur'
                    }],
                    newPassword: [
                        { required: true, validator: validatePass, trigger: 'blur' }
                    ],
                    newPassword1: [
                        { required: true, validator: validatePass2, trigger: 'blur' }
                    ],
                }
            }
        },
        mounted() {
            this.init()
        },
        methods: {
            init() {
                getUserDetail().then(res => {
                    const user = res.data.data;
                    this.form = {
                        id: user.id,
                        avatar: user.avatar,
                        name: user.name,
                        realName: user.realName,
                        phone: user.phone,
                        email: user.email,
                    }
                });
            },
            uploadFile(File) {
                this.loading=true;
                let file = File.file;
                uploadOss(file).then(result => {
                    if(result.hasOwnProperty('url')){
                        this.form.avatar = result.url;
                    }else{
                        this.$message({
                            type: "success",
                            message: '文件上传失败,请重新上传!'
                        })
                    }
                }).catch(err => {
                    this.$message({
                        type: "success",
                        message: '文件上传失败,请重新上传!'
                    })
                })
            },
            beforeAvatarUpload(file) {
                const isLt500K = file.size / 1024 < 500;
                 const isType = file.type == 'image/png' || file.type == 'image/jpeg'
                if(!isType) {
                    this.$message.error('上传头像图片只能是 JPG, PNG 格式!');
                }
                if (!isLt500K) {
                    this.$message.error('上传头像图片大小不能超过 500kb!');
                }
                return isType && isLt500K
            },
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        update(this.form).then(res => {
                            if (res.data.success) {
                                this.$message({
                                    type: "success",
                                    message: "修改信息成功!"
                                });
                            } else {
                                this.$message({
                                    type: "error",
                                    message: res.data.msg
                                });
                            }
                        })
                    } else {
                        return false;
                    }
                });
            },
            modifyPassword(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        updatePassword(this.passwordForm).then(res => {
                            if (res.data.success) {
                                this.$message({
                                    type: "success",
                                    message: "修改密码成功!"
                                });
                                this.$refs[formName].resetFields();
                            } else {
                                this.$message({
                                    type: "error",
                                    message: res.data.msg
                                });
                            }
                        })
                    } else {
                        return false;
                    }
                });
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            }
        }
    }
</script>

<style scoped lang="scss">
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
